<template>
  <div class="house-list">
    <el-card>
      <h3>成都房源管理</h3>

      <!-- 操作按钮和筛选区域 -->
      <el-row style="margin-bottom: 15px;" :gutter="20">
        <el-col :span="6">
          <el-button type="primary" @click="handleAdd">新增房源</el-button>
        </el-col>
        <el-col :span="18">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-input v-model="searchQuery" placeholder="搜索标题/地址" clearable @clear="resetSearch" @keyup.enter="applySearch">
                <template #append>
                  <el-button :icon="Search" @click="applySearch" />
                </template>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-select v-model="statusFilter" placeholder="房屋状态" clearable @change="filterHouses">
                <el-option label="全部" value="" />
                <el-option label="可出租" value="可出租" />
                <el-option label="已出租" value="已出租" />
                <el-option label="可出售" value="可出售" />
                <el-option label="已出售" value="已出售" />
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-slider
                  v-model="priceRange"
                  range
                  :min="0"
                  :max="10000"
                  :step="500"
                  @change="filterHouses"
              />
              <div style="text-align: center; margin-top: -10px;">
                <span>价格区间: {{ priceRange[0] }} - {{ priceRange[1] }} {{ priceUnit }}</span>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <!-- 房源表格 -->
      <el-table :data="paginatedHouses" border stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
        <el-table-column prop="title" label="标题" min-width="150" sortable>
          <template #default="{ row }">
            <el-link type="primary" @click="goToDetail(row.id)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="district" label="区域" width="120" sortable></el-table-column>
        <el-table-column prop="address" label="地址" min-width="200"></el-table-column>
        <el-table-column prop="price" label="价格" width="180" sortable>
          <template #default="{ row }">
            <div v-if="row.status === '可出租' || row.status === '已出租'">
              {{ row.price.toLocaleString() }} 元/月
            </div>
            <div v-else>
              {{ (row.price / 10000).toLocaleString() }} 万元
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="面积(m²)" width="100" sortable></el-table-column>
        <el-table-column prop="status" label="状态" width="120" sortable>
          <template #default="{ row }">
            <el-tag
                :type="getStatusTagType(row.status)"
                @click="toggleStatus(row)"
            >
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredHouses.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px;"
      />

      <!-- 弹窗表单 -->
      <el-dialog v-model="dialogVisible" :title="form.id ? '编辑房源' : '新增房源'" width="50%">
        <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域" prop="district">
                <el-select v-model="form.district" placeholder="请选择区域">
                  <el-option v-for="district in districts" :key="district" :label="district" :value="district" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交易类型" prop="transactionType">
                <el-select v-model="form.transactionType" placeholder="请选择交易类型" @change="handleTransactionTypeChange">
                  <el-option label="出租" value="rent" />
                  <el-option label="出售" value="sale" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="form.transactionType === 'rent' ? '月租金' : '售价'" prop="price">
                <el-input-number
                    v-model="form.price"
                    :min="0"
                    :step="form.transactionType === 'rent' ? 100 : 10000"
                    :precision="form.transactionType === 'rent' ? 0 : 2"
                />
                <span style="margin-left: 10px;">
                  {{ form.transactionType === 'rent' ? '元/月' : '万元' }}
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="面积" prop="area">
                <el-input-number v-model="form.area" :min="0" :step="5" />
                <span style="margin-left: 10px;">m²</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                  <el-option
                      v-for="status in getAvailableStatuses(form.transactionType)"
                      :key="status.value"
                      :label="status.label"
                      :value="status.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="户型" prop="layout">
                <el-select v-model="form.layout" placeholder="请选择户型">
                  <el-option label="一居室" value="一居室" />
                  <el-option label="两居室" value="两居室" />
                  <el-option label="三居室" value="三居室" />
                  <el-option label="四居室+" value="四居室+" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

const router = useRouter();

// 成都区域列表
const districts = [
  '锦江区', '青羊区', '金牛区', '武侯区', '成华区',
  '龙泉驿区', '新都区', '温江区', '双流区', '郫都区',
  '天府新区', '高新区', '东部新区'
];

// 生成100个成都房源数据
const generateHouses = () => {
  const houses = [];
  const statusOptions = [
    { type: 'rent', value: '可出租', label: '可出租' },
    { type: 'rent', value: '已出租', label: '已出租' },
    { type: 'sale', value: '可出售', label: '可出售' },
    { type: 'sale', value: '已出售', label: '已出售' }
  ];

  for (let i = 1; i <= 100; i++) {
    const district = districts[Math.floor(Math.random() * districts.length)];
    const layout = ['一居室', '两居室', '三居室', '四居室+'][Math.floor(Math.random() * 4)];
    const isRent = Math.random() > 0.5;
    const status = isRent
        ? statusOptions[Math.floor(Math.random() * 2)]
        : statusOptions[2 + Math.floor(Math.random() * 2)];

    const price = isRent
        ? Math.floor(Math.random() * 8000) + 1500 // 租金
        : (Math.floor(Math.random() * 300) + 100) * 10000; // 售价(万元)

    houses.push({
      id: i,
      title: `${district}${layout}${Math.random() > 0.5 ? '精装' : '简装'}房`,
      district,
      address: `成都市${district}${['路', '街', '大道'][Math.floor(Math.random() * 3)]}${Math.floor(Math.random() * 100) + 1}号`,
      price,
      area: Math.floor(Math.random() * 100) + 30,
      status: status.value,
      transactionType: isRent ? 'rent' : 'sale',
      layout
    });
  }

  return houses;
};

const houses = ref(generateHouses());
const loading = ref(false);
const dialogVisible = ref(false);
const form = ref({
  id: null,
  title: '',
  district: '',
  address: '',
  price: 0,
  area: 0,
  status: '可出租',
  transactionType: 'rent',
  layout: '一居室'
});

const searchQuery = ref('');
const statusFilter = ref('');
const priceRange = ref([0, 10000]);
const currentPage = ref(1);
const pageSize = ref(10);
const editingIndex = ref(-1);

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  district: [{ required: true, message: '请选择区域', trigger: 'change' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  area: [{ required: true, message: '请输入面积', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 获取当前价格单位
const priceUnit = computed(() => {
  if (statusFilter.value === '可出租' || statusFilter.value === '已出租') {
    return '元/月';
  } else if (statusFilter.value === '可出售' || statusFilter.value === '已出售') {
    return '万元';
  }
  return '元/月'; // 默认
});

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case '已出租': return 'danger';
    case '可出租': return 'success';
    case '已出售': return 'warning';
    case '可出售': return '';
    default: return 'info';
  }
};

// 获取可用的状态选项
const getAvailableStatuses = (transactionType) => {
  if (transactionType === 'rent') {
    return [
      { value: '可出租', label: '可出租' },
      { value: '已出租', label: '已出租' }
    ];
  } else {
    return [
      { value: '可出售', label: '可出售' },
      { value: '已出售', label: '已出售' }
    ];
  }
};

// 计算属性 - 筛选后的房源
const filteredHouses = computed(() => {
  let result = houses.value;

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(house =>
        house.title.toLowerCase().includes(query) ||
        house.address.toLowerCase().includes(query)
    );
  }

  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(house => house.status === statusFilter.value);
  }

  // 价格区间筛选
  result = result.filter(house => {
    const price = house.transactionType === 'rent' ? house.price : house.price / 10000;
    return price >= priceRange.value[0] && price <= priceRange.value[1];
  });

  return result;
});

// 分页后的数据
const paginatedHouses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredHouses.value.slice(start, end);
});

// 新增房源
function handleAdd() {
  form.value = {
    id: null,
    title: '',
    district: '',
    address: '',
    price: 0,
    area: 0,
    status: '可出租',
    transactionType: 'rent',
    layout: '一居室'
  };
  editingIndex.value = -1;
  dialogVisible.value = true;
}

// 编辑房源
function handleEdit(row) {
  const index = houses.value.findIndex(h => h.id === row.id);
  if (index !== -1) {
    form.value = JSON.parse(JSON.stringify(row));
    editingIndex.value = index;
    dialogVisible.value = true;
  }
}

// 删除房源
function handleDelete(id) {
  ElMessageBox.confirm('确定要删除这条房源信息吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    houses.value = houses.value.filter(house => house.id !== id);
    ElMessage.success('删除成功');
  }).catch(() => {});
}

// 切换状态
function toggleStatus(row) {
  if (row.transactionType === 'rent') {
    row.status = row.status === '可出租' ? '已出租' : '可出租';
  } else {
    row.status = row.status === '可出售' ? '已出售' : '可出售';
  }
  ElMessage.success('状态已更新');
}

// 交易类型变化处理
function handleTransactionTypeChange(val) {
  form.value.status = val === 'rent' ? '可出租' : '可出售';
  form.value.price = 0;
}

// 保存表单
function saveForm() {
  if (!form.value.title || !form.value.address) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  if (editingIndex.value === -1) {
    // 新增
    const newId = houses.value.length > 0 ? Math.max(...houses.value.map(h => h.id)) + 1 : 1;
    houses.value.push({ ...form.value, id: newId });
    ElMessage.success('新增成功');
  } else {
    // 修改
    houses.value[editingIndex.value] = { ...form.value };
    ElMessage.success('修改成功');
  }

  dialogVisible.value = false;
}

// 应用搜索
function applySearch() {
  currentPage.value = 1;
}

// 重置搜索
function resetSearch() {
  searchQuery.value = '';
  currentPage.value = 1;
}

// 筛选房源
function filterHouses() {
  currentPage.value = 1;
}

// 分页大小改变
function handleSizeChange(val) {
  pageSize.value = val;
  currentPage.value = 1;
}

// 当前页改变
function handleCurrentChange(val) {
  currentPage.value = val;
}

// 跳转到详情页
function goToDetail(id) {
  router.push(`/house/listdetail/${id}`);
}
</script>

<style scoped>
.house-list {
  padding: 20px;
}

.el-tag {
  cursor: pointer;
  margin-right: 5px;
}

.el-link {
  font-size: inherit;
}
</style>